package com.example.limiting.taskmanager2;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class PublishActivity extends Activity {
    private static final int ADD_REQUEST_CODE = 1;
    private static final int EDIT_REQUEST_CODE = 2;
    private static final int CONFIRM_RESULT_CODE = 1;
    private static final int CANCEL_RESULT_CODE = 2;
    private static final int DELETE_RESULT_CODE = 3;

    private static final String ADD_TYPE = "add";
    private static final String EDIT_TYPE = "edit";

    private WorkerAdapter workerAdapter;
    private ListViewForScrollView workerList;

    private String workers_for_select_data;

    private Button b1,b2;
    private TextView tv1,tv2;
    private Calendar c;
    private int m_year,m_month,m_day;
    private int m_year1,m_month1,m_day1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);

        Intent intent = getIntent();
        workers_for_select_data = intent.getStringExtra("workers");

        b1 = (Button)findViewById(R.id.button01);
        b2 = (Button)findViewById(R.id.button02);

        c = Calendar.getInstance();

        m_year = c.get(Calendar.YEAR);
        m_month = c.get(Calendar.MONTH);
        m_day = c.get(Calendar.DAY_OF_MONTH);

        m_year1 = c.get(Calendar.YEAR);
        m_month1 = c.get(Calendar.MONTH);
        m_day1 = c.get(Calendar.DAY_OF_MONTH);

        tv1 = (TextView)findViewById(R.id.textView01);

        tv1.setText(m_year+"-"+(m_month+1)+"-"+m_day);

        tv2 = (TextView)findViewById(R.id.textView02);
        tv2.setText(m_year1+"-"+(m_month1+1)+"-"+m_day1);

        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(0);
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(1);
            }
        });



        workerList = (ListViewForScrollView) findViewById(R.id.publish_worker_list);
        workerAdapter = new WorkerAdapter(PublishActivity.this,R.layout.worker_list_item);

        workerList.setAdapter(workerAdapter);
        workerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView workerName = (TextView) view.findViewById(R.id.worker_name);
                TextView workerContent = (TextView) view.findViewById(R.id.worker_content);

                Intent intent = new Intent();
                intent.setClass(PublishActivity.this, GetWorkerActivity.class);
                intent.putExtra("type", EDIT_TYPE);
                intent.putExtra("data", workers_for_select_data);
                intent.putExtra("worker_name", workerName.getText().toString());
                intent.putExtra("worker_content", workerContent.getText().toString());
                intent.putExtra("position", position);

                startActivityForResult(intent, EDIT_REQUEST_CODE);
            }
        });





    }


    protected Dialog onCreateDialog(int id) {
        if(id==0)
            return new DatePickerDialog(this,
                    l1,
                    m_year, m_month, m_day);
        else
            return new DatePickerDialog(this,
                    l2,
                    m_year1,m_month1,m_day1);
    }

    private DatePickerDialog.OnDateSetListener l1 = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            m_year = year;
            m_month = monthOfYear;
            m_day = dayOfMonth;
            tv1.setText(m_year+"-"+(m_month+1)+"-"+m_day);
        }
    };

    private DatePickerDialog.OnDateSetListener l2 = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            m_year1 = year;
            m_month1 = monthOfYear;
            m_day1 = dayOfMonth;
            tv2.setText(m_year1+"-"+(m_month1+1)+"-"+m_day1);
        }
    };



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_publish, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void addWorker(View view){
        Intent intent = new Intent();
        intent.setClass(PublishActivity.this, GetWorkerActivity.class);
        intent.putExtra("type", ADD_TYPE);
        intent.putExtra("data", workers_for_select_data);
        Log.e("workers",workers_for_select_data);
        startActivityForResult(intent, ADD_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        if(requestCode == ADD_REQUEST_CODE){
            switch (resultCode){
                case CONFIRM_RESULT_CODE:
                    Log.e("Publish", data.getStringExtra("worker_name") + " " +data.getStringExtra("worker_content"));
                    workerAdapter.add(new Worker(data.getStringExtra("worker_name"), data.getStringExtra("worker_content")));
                    workerList.deferNotifyDataSetChanged();
                    break;
                case CANCEL_RESULT_CODE:

                default:
            }
        }else if (requestCode == EDIT_REQUEST_CODE){
            int position;
            switch (resultCode){
                case CONFIRM_RESULT_CODE:
                    position = data.getIntExtra("position",-1);
                    Worker worker = new Worker(data.getStringExtra("worker_name"),data.getStringExtra("worker_content"));
                    workerAdapter.remove(workerAdapter.getItem(position));
                    workerAdapter.insert(worker,position);
                    workerList.deferNotifyDataSetChanged();
                    break;
                case CANCEL_RESULT_CODE:
                    break;
                case DELETE_RESULT_CODE:
                    position = data.getIntExtra("position",-1);
                    workerAdapter.remove(workerAdapter.getItem(position));
                    workerList.deferNotifyDataSetChanged();
                    break;
                default:
            }
        }


    }

    public void publishAction(View view)  {
        EditText TaskTitle = (EditText) findViewById(R.id.publish_title);
        Spinner TaskType = (Spinner) findViewById(R.id.Spinner01);
        CheckBox MonthTask = (CheckBox) findViewById(R.id.monthTask);
        TextView StartTime = (TextView) findViewById(R.id.textView01);
        TextView EndTime = (TextView) findViewById(R.id.textView02);
        EditText Detail = (EditText) findViewById(R.id.publish_content);
        JSONObject data = new JSONObject();
        try {
            data.put("title",TaskTitle.getText().toString());
            data.put("type",TaskType.getSelectedItemPosition() + 1);
            data.put("month_task",MonthTask.isChecked());
            data.put("start_time",StartTime.getText().toString());
            data.put("end_time",EndTime.getText().toString());
            data.put("detail",Detail.getText().toString());
            JSONArray jworkers = new JSONArray();
            for (int i = 0; i < workerAdapter.getCount(); i++) {
                Worker worker = workerAdapter.getItem(i);
                JSONObject jworker = new JSONObject();
                jworker.put("worker_name",worker.getWorkerName());
                jworker.put("worker_content",worker.getWorkerContent());
                jworkers.put(jworker);
            }
            data.put("workers_list",jworkers);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new PublishTask().execute(data.toString());


    }

    private class PublishTask extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... params) {
            HttpHelper httpHelper = new HttpHelper(PublishActivity.this);
            String result = null;
            try {
                Log.e("PbTask",params[0]);
                result = httpHelper.PublishToServer(params[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            if(!result.isEmpty()){
                JSONTokener jsonParser = new JSONTokener(result);
                try {
                    JSONObject body = (JSONObject) jsonParser.nextValue();
                    JSONObject data = body.getJSONObject("data");
                    String resu = data.getString("result");
                    if (resu.equals("True")){
                        Toast.makeText(PublishActivity.this,"已发布！",Toast.LENGTH_SHORT).show();
                        finish();
                    }else{
                        Toast.makeText(PublishActivity.this,"你无权发布任务！",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }else{
                Toast.makeText(PublishActivity.this,"网络状态不好，请重试！",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
